package com.stox.client.ui.javafx.widget;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;

import com.stox.client.ui.javafx.core.StoxPlatform;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.util.Constant;

public class InformativeProgressBar extends StackPane {

	private final ProgressBar progressBar = new ProgressBar();
	private final Label doneLabel = new Label();
	private final Label remainingLabel = new Label();
	private final HBox infoPanel = new HBox(doneLabel, remainingLabel);
	
	public InformativeProgressBar() {
		UI.style(this, CSS.informativeProgressBar);
		infoPanel.setMaxWidth(Double.MAX_VALUE);
		progressBar.setMaxWidth(Double.MAX_VALUE);
		doneLabel.setMaxWidth(Double.MAX_VALUE);
		remainingLabel.setMaxWidth(Double.MAX_VALUE);

		HBox.setHgrow(doneLabel, Priority.ALWAYS);
		doneLabel.setAlignment(Pos.CENTER_LEFT);
		
		remainingLabel.setAlignment(Pos.CENTER_RIGHT);
		HBox.setHgrow(remainingLabel, Priority.ALWAYS);
		
		progressBar.progressProperty().addListener(new ChangeListener<Number>(){
			@Override
			public void changed(ObservableValue<? extends Number> observable,
					Number oldValue, Number value) {
				doneLabel.setText(Constant.numberFormat.format(value.doubleValue()*100)+"%");
				remainingLabel.setText(Constant.numberFormat.format((1-value.doubleValue())*100)+"%");
			}
		});
		
		
		getChildren().addAll(progressBar,infoPanel);
	}
	
	public void setProgress(double progress){
		if(Platform.isFxApplicationThread()){
			progressBar.setProgress(progress);
		}else{
			StoxPlatform.runLater(new Runnable(){
				@Override
				public void run() {
					progressBar.setProgress(progress);
				}
			});
		}
	}
	
}
